package com.example.servicedemo;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;

public class Activity2 extends AppCompatActivity {

    private static final String TAG = "Activity2";

    private Messenger messenger;

    private ServiceConnection serviceConnection = new ServiceConnection() {
        // 绑定
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            messenger = new Messenger(service);
            Log.i(TAG, "绑定");
        }
        // 解绑
        @Override
        public void onServiceDisconnected(ComponentName name) {
            messenger = null;
            Log.i(TAG, "解绑");
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_2);

        // 启动绑定服务
        findViewById(R.id.button_startAndBind).setOnClickListener(v -> {
            startService(new Intent(this, MyService2.class));
            bindService(new Intent(this, MyService2.class), serviceConnection, Context.BIND_AUTO_CREATE);
        });
        // 发送消息给Service
        findViewById(R.id.button_sendMsgToService).setOnClickListener(v -> {
            if (messenger != null) {
                Message message = Message.obtain();
                message.what = 0;
                message.obj = "对象";
                message.arg1 = 11;
                message.arg2 = 22;
                try {
                    messenger.send(message);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}